package br.com.sendmail.util;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 * 30/11/2012 - LoadDadosXML.java 
 * Elton Souza - eltonds88@gmail.com
 *
 * Classe auxiliar para carregar os dados de contas e templates
 * do aquivo sen-mail.xml
 * 
 */
public class LoadDadosXML {

	public LoadDadosXML() {
		super();
	}

	protected Node getElement(Document doc, int opt, String element) throws Exception {
		Element root = null;
		Node node = null;
		if(doc!=null) {
			root = doc.getDocumentElement();
			if(root != null) {
				node = root.getElementsByTagName(element).item(opt);
			} else {
				throw new Exception("Erro ao ler documento!");
			}
		} else {
			throw new Exception("Documento nao localizado!");
		}
		return node;
	}

	protected String getValue(Element n, int opt, String element) throws Exception {		
		Node node = null;
		if(n!=null) {
			node = n.getElementsByTagName(element).item(opt);			
		} else {
			throw new Exception("O elemento nao foi localizado");
		}
		if(node!=null) {			
			return node.getFirstChild().getNodeValue();
		} else {
			return null;
		}
	}

	protected Document getArquivo(String arquivo) {
		File file = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document doc = null;

		try {
			file = new File(arquivo);
			db = dbf.newDocumentBuilder();
			doc = db.parse(file);		
		} catch(IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e2) {			
			e2.printStackTrace();
		} catch (SAXException e3) {			
			e3.printStackTrace();
		}

		return(doc);
	}
}
